package com.penglecode.netty3.example1;

import java.nio.charset.Charset;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelEvent;

public class MessageUtils {

	public static final Charset defaultCharset = Charset.forName("UTF-8");
	
	public static String getMessage(Object message){
		if(message == null){
			throw new IllegalArgumentException("args 'message' can not be null!");
		}
		if(message instanceof ChannelBuffer){
			return new String(((ChannelBuffer) message).toString(defaultCharset));
		}
		throw new IllegalArgumentException("unsupported message type: " + message.getClass());
	}

	public static String getMessage(Object message, Charset charset){
		if(charset == null){
			charset = defaultCharset;
		}
		if(message == null){
			throw new IllegalArgumentException("args 'message' can not be null!");
		}
		if(message instanceof ChannelBuffer){
			return new String(((ChannelBuffer) message).toString(charset));
		}
		throw new IllegalArgumentException("unsupported message type: " + message.getClass());
	}
	
	public static void sendMessage(ChannelEvent event, String messageText){
		if(event == null){
			throw new IllegalArgumentException("args 'event' can not be null!");
		}
		if(messageText == null || messageText.equals("")){
			return;
		}
		byte[] totalBytes = messageText.getBytes(defaultCharset);
		ChannelBuffer message = ChannelBuffers.buffer(totalBytes.length);
		message.writeBytes(totalBytes);
		event.getChannel().write(message);
	}
	
	public static void sendMessage(ChannelEvent event, String messageText, Charset charset){
		if(charset == null){
			charset = defaultCharset;
		}
		if(event == null){
			throw new IllegalArgumentException("args 'event' can not be null!");
		}
		if(messageText == null || messageText.equals("")){
			return;
		}
		byte[] totalBytes = messageText.getBytes(charset);
		ChannelBuffer message = ChannelBuffers.buffer(totalBytes.length);
		message.writeBytes(totalBytes);
		event.getChannel().write(message);
	}
	
}
